﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Messaging;
using PortalMainService.Dominio;
using System.Xml.Serialization;
using System.IO;




namespace WcfConsulta
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Consultas" in code, svc and config file together.
    public class Consultas : IConsultas
    {
        public void DoWork()
        {
        }

        public string EnviarConsulta(Consultamail consulta)
        {
            

            string rutaCola = @".\private$\Correos2";
            
                if (!MessageQueue.Exists(rutaCola))
                    MessageQueue.Create(rutaCola);

                MessageQueue cola = new MessageQueue(rutaCola);
                Message mensaje = new Message();
                mensaje.Label = "Nuevo correo";
                mensaje.Body = consulta;
                cola.Send(mensaje);
                    

            return "Correo en proceso";

            }

        public string QueueMessage(EmailMessage message)
        {
            Message msg = new Message();
            msg.Body = message;
            msg.Recoverable = true;
            msg.Formatter = new BinaryMessageFormatter();
            string queuePath = @".\private$\WebsiteEmails";
            MessageQueue msgQ;

            //if this queue doesn't exist we will create it
            ColaExiste(queuePath);

            msgQ = new MessageQueue(queuePath);
            msgQ.Formatter = new BinaryMessageFormatter();
            msgQ.Send(msg);

            return "ENVIO CORRECTO";
        }

        public static void ColaExiste(string queuePath)
        {
            //if this queue doesn't exist we will create it
            if (!MessageQueue.Exists(queuePath))
                MessageQueue.Create(queuePath);
        }

        public string SendMessage(EmailMessage message, string username, string password, bool enableSsl)
        {

            string serializedMessage = SerializeMessage(message);
            string correos = message.To;
            var mails = correos.Split(';');

            SmtpClient sc = new SmtpClient();
            //sc.Timeout = 250;//Tiempo de conexión
            sc.Host = "smtp.gmail.com";
            sc.EnableSsl = true;
            sc.Credentials =
            new System.Net.NetworkCredential
            {
                UserName = username,//Nombre de usuario de correo
                Password = password//password
            };


            using (MailMessage mm = new MailMessage())
            {
                mm.From = new System.Net.Mail.MailAddress(message.From, message.From, System.Text.Encoding.UTF8);
                mm.Subject = message.Subject;

                //Cargamos el contenido del mail.
                mm.Body = message.Message;
                mm.Priority = MailPriority.Normal;

                //Cargamos todos los mails que se ingresaron
                //en el campor de text
                foreach (string dir in mails)
                    mm.To.Add(dir);


                //CorreoLog repository = new CorreoLog();

                try
                {
                    sc.Send(mm);
                    //repository.LogMessage(serializedMessage, true);
                    return "Correo enviado";
                    //add to logging db
                }
                catch (Exception ex)
                {
                    //add to logging db
                    //repository.LogMessage(serializedMessage, false);
                    return "Correo no Enviado " + ex.Message;
                    //throw;
                }

            }

        }

        public static string SerializeMessage(EmailMessage message)
        {
            //string result = "text.txt";
            /*MemoryStream oMemoryStream = new MemoryStream();
            StreamWriter tw = new StreamWriter(oMemoryStream, Encoding.Unicode);
            XmlSerializer x = new XmlSerializer(message.GetType());
            x.Serialize(tw, message);
            return tw.ToString();*/
            XmlSerializer oXmlSerializer = null;

            using (MemoryStream oMemoryStream = new MemoryStream())
            {
                using (StreamWriter oStreamWriter = new StreamWriter(oMemoryStream, Encoding.Unicode))
                {
                    oXmlSerializer = new XmlSerializer(message.GetType());
                    oXmlSerializer.Serialize(oStreamWriter, message);
                    int i_Puntero = (int)oMemoryStream.Length;
                    byte[] arr_Bytes = new byte[i_Puntero];
                    oMemoryStream.Seek(0, SeekOrigin.Begin);
                    oMemoryStream.Read(arr_Bytes, 0, i_Puntero);
                    UnicodeEncoding UE = new UnicodeEncoding();
                    return UE.GetString(arr_Bytes).Trim();
                }
            }

        }
  
    }

    public class Consultamail
    {
        public string correo { get; set; }
        public String Mensaje { get; set; }
    } 
}

